﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TimKen.DataEntity;
using TimKen.BussLogic;
using TimKen.App;
using System.Data;
using System.Text;
using TimKen.DataAccess;

namespace TimKen.Web.Admin.Product
{
    public partial class Product_Info : TimKen.App.AdminPage
    {
        private ProductManager productManager = new ProductManager();
        private PDescriptionManager descriptionManager = new PDescriptionManager();
        private PAttributeManager attributeManager = new PAttributeManager();
        private PCategoryManager categoryManager = new PCategoryManager();

        public override string ActionCode
        {
            get
            {
                return "88";
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["ProductID"] != null && TypeParse.IsNumeric(Request.QueryString["ProductID"]))
                {
                    ProductID = Convert.ToInt32(Request.QueryString["ProductID"]);
                }
                BindBrandList();
                BinddplType();
                BindData();
            }
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.btnUpload);
            BindResources();
        }

        public int ProductID
        {
            get
            {
                if (ViewState["ProductID"] != null && TypeParse.IsNumeric(ViewState["ProductID"]))
                    return Convert.ToInt32(ViewState["ProductID"]);
                else
                    return 0;
            }
            set
            {
                ViewState["ProductID"] = value;
            }
        }

        private void BindData()
        {
            TimKen.DataEntity.Product product = productManager.GetModel(ProductID);
            TimKen.DataEntity.PDescription description = descriptionManager.GetModel(ProductID, LanguageID);

            if (product != null)
            {
                txtProductID.Value = product.ProductID.ToString();
                txtBasicPrice.Text = GetProductBasePrice(product.ProductID);
                txtCurrency.Text = product.Currency;
                txtDateAdded.Text = product.DateAdded.ToShortDateString();
                txtInvQty.Text = product.InvQty.ToString();
                txtItemCode.Text = product.ItemCode;
                txtLastModified.Text = product.LastModified.Value.ToShortDateString();
                txtTaxRate.Text = product.TaxRate.ToString();
                txtBaseUnit.Text = GetUnit(product.BaseUnit);
                txtSalesUnit.Text = GetUnit(product.SalesUnit.ToString());
                txtVaild.Text = GetBoolPic(product.Vaild);
                txtVailTo.Text = product.VailTo.ToString();
                txtValidFrom.Text = product.ValidFrom.Value.ToShortDateString();
                txtFreeze.Text = GetBoolPic(product.Freeze);
                txtFreezeTo.Text = product.FreezeTo.Value.ToShortDateString();
                txtFreezeFrom.Text = product.FreezeFrom.Value.ToShortDateString();
                txtMinMultiple.Text = product.MinMultiple.ToString();
                txtMinNumber.Text = product.MinNumber.ToString();
                for (int i = 0; i < this.ddlBrand.Items.Count; i++)
                {
                    if (this.ddlBrand.Items[i].Value == product.BrandID.ToString())
                        this.ddlBrand.Items[i].Selected = true;
                }
                txtWeight.Text = product.Weight.ToString();
                txtIntroDocFile.Text = product.IntroDocFiles;
                string image = product.Image;
                if (!string.IsNullOrEmpty(image))
                {
                    imgProductImage.Visible = true;
                    imgProductImage.ImageUrl = UploadFilePathForProduct + image;
                }
                else
                    imgProductImage.Visible = false;
                lbDiffPrice.Text = GetDiffPrice(product.ItemCode);
                ddlCategory.SelectedValue = product.CategoryID.ToString();
                cbRecommend.Checked = product.IsRecommend;
            }

            if (product != null)
            {
                txtProductName.Text = description.Name;
                fckContent.Value = description.Description;

                for (int i = 0; i < this.ddlCategory.Items.Count; i++)
                {
                    if (this.ddlCategory.Items[i].Value == product.CategoryID.ToString())
                        this.ddlCategory.Items[i].Selected = true;
                }
            }
        }

        protected void BindResources()
        {
            this.fckContent.DefaultLanguage = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString().ToLower();
            btnSubmit.Text = GetLangString("Save");
            btnUpload.Text = GetLangString("Upload");
            btnDelete.Text = GetLangString("Delete");
        }

        private string GetDiffPrice(string itemCode)
        {
            DataSet ds = productManager.GetPDiffPriceByProductCode(itemCode);
            StringBuilder sb = new StringBuilder();

            if (ds.Tables[0].Rows.Count > 0)
            {
                sb.Append("<table id=\"DiffPrice\" class=\"list-div\"><tr><td><=</td><td>Price/Discount</td>");

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (dr["type"].ToString() == "0")
                    {
                        sb.Append("<tr><td>" + dr["Qty"].ToString() + "</td><td>" + dr["Discount"].ToString() + "</td></tr>");
                    }
                    else
                    {
                        sb.Append("<tr><td>" + dr["Qty"].ToString() + "</td><td>" + dr["Price"].ToString() + "</td></tr>");
                    }
                }
                sb.Append("</table>");
            }
            else
            {
                sb.Append("");
            }
            return sb.ToString();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            bool fileOK = false;
            string fileExtension = string.Empty;

            TimKen.DataEntity.Product product = productManager.GetModel(ProductID);
            if (this.fuProductImage.HasFile)
            {
                fileExtension = System.IO.Path.GetExtension(fuProductImage.FileName).ToLower();

                string[] allowedExtensions = { ".gif", ".jpg", ".png", ".bmp", };

                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                }
            }
            if (fileOK)
            {
                this.imgProductImage.Visible = true;

                try
                {
                    string fileName = product.ItemCode + System.DateTime.Now.ToString("yyyyMMddhhmmss") + fileExtension;
                    this.fuProductImage.SaveAs(PhysicalUploadFilePathForProduct + fileName);
                    this.imgProductImage.ImageUrl = UploadFilePathForProduct + fileName;

                    fileName = UploadFilePathForProduct + fileName;
                    productManager.UploadImg(ProductID, fileName);
                    Alert(GetLangString("UploadSuccessful"));
                }
                catch
                {
                    Alert(GetLangString("UploadFailure"));
                }
                finally
                {
                }
            }

            else
            {
                Alert(GetLangString("UploadFailure"));
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            TimKen.DataEntity.Product product = productManager.GetModel(ProductID);
            if (this.fuProductImage.HasFile && !string.IsNullOrEmpty(product.Image))
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(PhysicalUploadFilePathForProduct + product.Image);
                if (fileInfo.Exists)
                {
                    try
                    {
                        fileInfo.Delete();

                        this.imgProductImage.Visible = false;
                        this.imgProductImage.ImageUrl = "";

                        //更新产品信息
                        product.Image = "";
                        productManager.Update(product);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("删除失败,错误信息" + ex.Message);
                    }
                }
            }

            else
            {
                Alert(GetLangString("UploadFailure"));
            }
        }
        private void BinddplType()
        {
            ddlCategory.Items.Clear();
            TimKen.BussLogic.PCategoryManager cm = new PCategoryManager();
            ddlCategory.DataSource = cm.GetAllLeafCategory(LanguageWhereStr);
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataBind();
            ddlCategory.Items.Insert(0, new ListItem(GetLangString("ItemForSelect"), "0"));
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ///描述信息
            PDescription description = descriptionManager.GetModel(ProductID, LanguageID);
            description.Description = this.fckContent.Value;
            descriptionManager.Update(description);

            //产品
            DataEntity.Product product = productManager.GetModel(ProductID);
            string oldTypeID = product.CategoryID.ToString();
            product.CategoryID = Convert.ToInt32(this.ddlCategory.SelectedValue);
            product.BrandID = Convert.ToInt32(this.ddlBrand.SelectedValue);

            product.IntroDocFiles = txtIntroDocFile.Text.Trim();
            product.IsRecommend = cbRecommend.Checked;
            productManager.Update(product);

            if (this.ddlCategory.SelectedValue != oldTypeID)
            {
                attributeManager.Delete(ProductID);
            }

            //产品属性
            if (Request.Form["OptionIDs"] != null)
            {
                string[] optionIDs = Request.Form["OptionIDs"].Split(',');

                foreach (string optionID in optionIDs)
                {
                    string Envalue = Request.Form["att_" + optionID + "en"];

                    DataEntity.PAttribute attributeEn = new TimKen.DataEntity.PAttribute();
                    attributeEn.LanguageID = (int)LanguageEnum.English;
                    attributeEn.OptionID = int.Parse(optionID);
                    attributeEn.OptionValue = Envalue;
                    attributeEn.ProductID = ProductID;

                    string Cnvalue = Request.Form["att_" + optionID + "cn"];

                    DataEntity.PAttribute attributeCn = new TimKen.DataEntity.PAttribute();
                    attributeCn.LanguageID = (int)LanguageEnum.Chinese;
                    attributeCn.OptionID = int.Parse(optionID);
                    attributeCn.OptionValue = Cnvalue;
                    attributeCn.ProductID = ProductID;




                    if (this.ddlCategory.SelectedValue != oldTypeID)
                    {
                        attributeManager.Add(attributeEn);
                        attributeManager.Add(attributeCn);
                    }
                    else
                    {
                        attributeManager.Update(attributeEn);
                        attributeManager.Update(attributeCn);
                    }
                }
            }

            Response.Redirect(Request.RawUrl);

        }

        private void BindBrandList()
        {
            string sql = "SELECT  BrandID,Name FROM PBrand";
            SqlDataReader reader = DataAccess.DbHelperSQL.ExecuteReader(sql);
            while (reader.Read())
            {
                this.ddlBrand.Items.Add(new ListItem(reader["Name"].ToString(), reader["BrandID"].ToString()));
            }

            reader.Close();
            reader.Dispose();
        }

    }
}
